import deviceManager from '@ohos.distributedHardware.deviceManager';

var SUBSCRIBE_ID = 100;
const DEVICE_STATE_CHANGE = 'deviceStateChange';
const DEVICE_FOUND = "deviceFound";
const DISCOVER_FAIL = "discoverFail";
const SERVICE_DIE = "serviceDie";

export default class RemoteDeviceModel {
    deviceList = [];// 可信设备列表
    discoverList = [];// 发现设备列表
    callback;
    #deviceManager;

    constructor() {
    }

    // 注册设备列表回调
    registerDeviceListCallback(callback) {
        console.info("[RemoteDeviceModel] registerDeviceListCallback")
        if (typeof (this.#deviceManager) === 'undefined') {
            // 获取设备管理对象
            let self = this;
            deviceManager.createDeviceManager('com.nlas.focusgame',
                (error, value) => {
                    if (error) {
                        console.error('[RemoteDeviceModel] createDeviceManager failed.');
                        return;
                    }
                    self.#deviceManager = value;// 设备管理器对象实例
                    self.registerDeviceListCallback_(callback);
                })
        } else {
            this.registerDeviceListCallback_(callback);
        }
    }

    registerDeviceListCallback_(callback) {
        console.info('[RemoteDeviceModel] registerDeviceListCallback_');
        this.callback = callback;
        if (typeof (this.#deviceManager) === 'undefined') {
            console.error('[RemoteDeviceModel] deviceManager has not initialized');
            this.callback();
            return;
        }

        // 同步获取所有可信设备列表
        var list = this.#deviceManager.getTrustedDeviceListSync();
        console.info('[RemoteDeviceModel] deviceList=' + JSON.stringify(list));
        if (typeof (list) != 'undefined' && typeof (list.length) != 'undefined') {
            this.deviceList = list;// list包含：deviceId、deviceName、deviceType
        }
        this.callback();

        let self = this;
        // 注册分布式监听器--设备状态变化
        // 可以参看API：https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-device-manager.md#devicemanager
        this.#deviceManager.on(DEVICE_STATE_CHANGE, (data) => {
            if (typeof (data) === 'undefined') {
                console.error("[RemoteDeviceModel]  data undefined");
                return;
            }
            console.info('[RemoteDeviceModel] deviceStateChange data=' + JSON.stringify(data));
            switch (data.action) {
                case 0:
                {
                    // 设备上线
                    console.info('[RemoteDeviceModel] online, updated device list=' + JSON.stringify(self.deviceList));
                    // 实际证明，返回的设备信息与原来的设备信息存在差异：deviceId、deviceName、deviceType、networkId
                    // 源数据：data={"subscribeId":20226,"device":{"deviceId":"2762998A243A9F2746FFF1FE7546736F7171C3FC089F39FD4BC987AD76379717","networkId":"","deviceName":"OpenHarmony","deviceType":175}}
                    // 返回：data={"action":0,"device":{"deviceId":"09f70e8e0e85d0523454ffe58d0a851dfe05c30073a1aa8a2306233e43750b30","networkId":"09f70e8e0e85d0523454ffe58d0a851dfe05c30073a1aa8a2306233e43750b30","deviceName":"OpenHarmony 3.1 Release","deviceType":0}}
                    // 去重处理
                    let deviceCount = self.deviceList.length;
                    if (deviceCount > 0) {
                        for(var i = 0; i < deviceCount; i++) {
                            if (self.deviceList[i].deviceId === data.device.deviceId) {
                                console.info("[RemoteDeviceModel] online, device already exist");
                                return;
                            }
                        }
                    }
                    self.deviceList[deviceCount] = data.device;
                    self.callback();
                    break;
                }
                case 2:
                {
                    // 设备下线
                    console.info('[RemoteDeviceModel] offline, updated device list=' + JSON.stringify(data.device));
                    const count = self.deviceList.length;
                    if (count > 0) {
                        var list = [];
                        // 过滤出所有在线的设备
                        for (var i = 0; i < count; i++) {
                            if (self.deviceList[i].deviceId != data.device.deviceId) {
                                list[i] = data.device;
                            }
                        }
                        self.deviceList = list;
                    }

                    self.callback();
                    break;
                }
                case 3:
                {
                    console.info('[RemoteDeviceModel] change, updated device list=' + JSON.stringify(self.deviceList));
                    if (self.deviceList.length > 0) {
                        // 修改设备状态
                        for (var i = 0; i < self.deviceList.length; i++) {
                            if (self.deviceList[i].deviceId === data.device.deviceId) {
                                self.deviceList[i] = data.device;
                                break;
                            }
                        }
                    }
                    self.callback();
                    break;
                }
                default:
                    break;
            }
        });

        // 发现设备
        this.#deviceManager.on(DEVICE_FOUND, (data) => {
            console.info('[RemoteDeviceModel] deviceFound data=' + JSON.stringify(data));
            if (data == null) {
                return;
            }
            const count = self.discoverList.length;
            for (var i = 0; i < count; i++) {
                if (self.discoverList[i].deviceId === data.device.deviceId) {
                    // 设备已经在列表中
                    return;
                }
            }
            // 新增发现的设备
            self.discoverList[count] = data.device;
            console.info('[RemoteDeviceModel] deviceFound finish');
            self.callback();
        });

        this.#deviceManager.on(DISCOVER_FAIL, (data) => {
            console.info('[RemoteDeviceModel] discoverFail data=' + JSON.stringify(data));
        });
        this.#deviceManager.on(SERVICE_DIE, () => {
            console.error('[RemoteDeviceModel] serviceDie');
        });

        // 随机数
        SUBSCRIBE_ID = Math.floor(65536 * Math.random());
        var info = {
            subscribeId: SUBSCRIBE_ID,// 服务订阅ID【0~65535】，对每个发现进程来说应该是唯一的
            mode: 0xAA,//主动模式
            medium: 2,//订阅媒介 2-wifi
            freq: 2,// 订阅频率 高
            isSameAccount: false,// 只能找到帐号相同的设备
            isWakeRemote: true,// 找到睡眠设备
            capability: 0
        };
        console.info('[RemoteDeviceModel] startDeviceDiscovery ' + SUBSCRIBE_ID);
        this.#deviceManager.startDeviceDiscovery(info);// 发现设备
    }

    /**
     * 设备认证
     * @param deviceId 设备ID
     * @param callback 回调
     */
    authDevice(deviceId, callback) {
        console.info('[RemoteDeviceModel] authDevice ' + deviceId);
        for (var i = 0; i < this.discoverList.length; i++) {
            if (this.discoverList[i].deviceId === deviceId) {
                // 在线设备中存在此设备,创建扩展信息
                let extraInfo = {
                    "targetPkgName": 'com.ohos.distributedRemoteStartFA',
                    "appName": 'demo',
                    "appDescription": 'demo application',
                    "business": '0'
                };
                let authParam = {
                    "authType": 1,// 认证类型，1为pin码。
                    "appIcon": '',
                    "appThumbnail": '',
                    "extraInfo": extraInfo // 扩展信息：key-value
                };
                console.info('[RemoteDeviceModel] authenticateDevice ' + JSON.stringify(this.discoverList[i]));
                this.#deviceManager.authenticateDevice(this.discoverList[i], authParam, (err, data)=>{
                    console.info('[RemoteDeviceModel] authenticateDevice, data=' + JSON.stringify(data) + ";err=" + JSON.stringify(err));
                    let code = 0;
                    if (typeof(err) != 'undefined') {
                        code = err.code;
                    }
                    callback({
                        code: code
                    });
                })
            }
        }
    }

    unregisterDeviceListCallback() {
        console.info('[RemoteDeviceModel] stopDeviceDiscovery ' + SUBSCRIBE_ID);
        this.#deviceManager.stopDeviceDiscovery(SUBSCRIBE_ID);
        this.#deviceManager.off(DEVICE_STATE_CHANGE);
        this.#deviceManager.off(DEVICE_FOUND);
        this.#deviceManager.off(DISCOVER_FAIL);
        this.#deviceManager.off(SERVICE_DIE);
        this.deviceList = [];
        this.discoverList = [];
    }
}